//
//  FitureCustomPresetnAnimatiion.swift
//  taurus
//
//  Created by 刘艺 on 2021/8/16.
//  Copyright © 2021 com.fiture. All rights reserved.
//

import UIKit

class FitureCustomPresentAnimation: NSObject {
    var config = FitureCustomPresentConfig()
    var maskViewTapBlock: (() -> Void)?
    init(config: FitureCustomPresentConfig,
         maskTapHandler: (() -> Void)?) {
        super.init()
        self.config = config
        self.maskViewTapBlock = maskTapHandler
    }
}

extension FitureCustomPresentAnimation: UIViewControllerAnimatedTransitioning {

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        0.25
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let toVC = transitionContext.viewController(forKey: .to) else { return }
        let containerView = transitionContext.containerView
        /// 模态的背景遮罩
        let maskview = FitureCustomPresentMaskView()
        maskview.frame = containerView.bounds
        maskview.touchesBeganBlock = maskViewTapBlock
        containerView.addSubview(maskview)

        containerView.addSubview(toVC.view)

        let finalFrame = CGRect(x: 0,
                                y: UIScreen.main.bounds.size.height - config.containerViewControllerHeight,
                                width: containerView.frame.size.width,
                                height: config.containerViewControllerHeight)
        toVC.view.frame = CGRect(x: finalFrame.origin.x,
                                 y: UIScreen.main.bounds.size.height,
                                 width: finalFrame.width,
                                 height: finalFrame.height)
        let duration = transitionDuration(using: transitionContext)
        UIView.animate(withDuration: duration) {
            toVC.view.frame = finalFrame
            maskview.alpha = self.config.maskColorAlpha
        } completion: { _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            if transitionContext.transitionWasCancelled {
                maskview.alpha = 0
            }
        }
    }
}
